package com.handong.handserialprogram.module.base;

import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.status.EmergencyResponse;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.ViewUtil;

import me.shaohui.bottomdialog.BottomDialog;

/**
 * 紧急报警界面
 * Created by userKey on 2017/12/1.
 */

public abstract class EmergencyActivity<P extends BasePresenter> extends BaseActivity<P> {

    private boolean mEmergencyAlarming = false;

//    private boolean mIsDisplayInfo=false;
    /**
     * 紧急报警确认对话框。
     */
    private BottomDialog mSureDialog;
    /**
     * 报警对话框。
     */
    private MaterialDialog mReportServerDialog;
    /**
     * 是否正在紧急报警。
     */
    private MaterialDialog mResultDialog;

    private ImageView mFileIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sureDialogNegative://取消
                mSureDialog.dismiss();
//                mIsDisplayInfo=false;
                break;

            case R.id.sureDialogPositive://报警
                mSureDialog.dismiss();
                initReportServerDialog();
//                mIsDisplayInfo=false;
                break;
        }
    }

    /**
     * 弹出报警框
     */
    public void askUserForEmergency() {
        showBottomDialog();
    }

    /**
     * 发送紧急报警
     */
    public void sendEmergencyRequest() {
        initReportServerDialog();
    }

    /**
     * 处理紧急报警返回
     */
    public void dealEmergencyResponse(EmergencyResponse response) {
        communicateServer(response);
    }

    private boolean isShowF1Emergency() {
        if (!mIsResume) {
            return false;
        }
        if (isLoadingShowing()) {
            AppUtil.showShortToast(getApplicationContext(), "正在执行其他操作");
            return false;
        }
        if (mReportServerDialog != null && mReportServerDialog.isShowing()) {
            return false;
        }
        if (mResultDialog != null && mResultDialog.isShowing()) {
            mResultDialog.dismiss();
        }
        return true;
    }

    /**
     * 报警确认对话框。
     */
    private void showBottomDialog() {
        if (!isShowF1Emergency()) {
            return;
        }
//        if (mIsDisplayInfo)
//            return;
//        mIsDisplayInfo=true;
        if (mSureDialog == null) {
            mSureDialog = BottomDialog.create(getSupportFragmentManager());
            mSureDialog.setLayoutRes(R.layout.dialog_sure_report);
            mSureDialog.setCancelOutside(false);
            mSureDialog.setDimAmount(0.75f);
            mSureDialog.setViewListener(new BottomDialog.ViewListener() {
                @Override
                public void bindView(View v) {
                    bindClickListener(v);
                    //mSureDialog.getDialog().getWindow().setFlags(ViewUtil.FLAG_HOMEKEY_DISPATCHED, ViewUtil.FLAG_HOMEKEY_DISPATCHED);
                }
            });
        }
        if (mSureDialog.getDialog() == null || !mSureDialog.getDialog().isShowing()) {
            mSureDialog.show();
        }
    }

    /**
     * 绑定点击事件
     */
    private void bindClickListener(View view) {
        TextView btnPositive = (TextView) view.findViewById(R.id.sureDialogPositive);
        btnPositive.setOnClickListener(this);
        TextView btnNegative = (TextView) view.findViewById(R.id.sureDialogNegative);
        btnNegative.setOnClickListener(this);
    }

    /**
     * 发送紧急报警
     */
    private void initReportServerDialog() {
        if (!isShowF1Emergency()) {
            return;
        }
        mEmergencyAlarming = true;

        /**
         * 发送紧急报警。
         */
        SerialPortUtil serialPort = SerialPortUtil.getInstance(this);
        serialPort.emergencyAlarm2Server();

        if (mReportServerDialog == null) {
            View customView = LayoutInflater.from(this).inflate(R.layout.dialog_report_server, null);

            mReportServerDialog = new MaterialDialog.Builder(this)
                    .canceledOnTouchOutside(false)
                    .customView(customView, true)
                    .autoDismiss(false)
                    .dismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            if (mFileIcon != null)
                                mFileIcon.clearAnimation();
                        }
                    }).build();
        }

        if (mFileIcon == null) {
            mFileIcon = (ImageView) mReportServerDialog.getCustomView().findViewById(R.id.reportFileIcon);

            ImageView phone = (ImageView) mReportServerDialog.getCustomView().findViewById(R.id.reportServerPhone);
            AnimationDrawable drawable = (AnimationDrawable) phone.getBackground();
            drawable.start();
            drawable.setOneShot(false);
        }
        //if (mFileIcon != null){
        //AnimationDrawable drawable = (AnimationDrawable) mFileIcon.getDrawable();
        //            if (!drawable.isRunning()){
        //                drawable.run();
        //drawable.start();
        //            }
        //        }
        addAnim(mFileIcon);
        if (mSureDialog != null && mSureDialog.getDialog() != null && mSureDialog.getDialog().isShowing()) {
            mSureDialog.dismiss();
        }
        ViewUtil.removeHomeKeyListener(mReportServerDialog);
    }

    /**
     * 给View添加动画。
     *
     * @param view Android控件。
     */
    protected void addAnim(final View view) {
        Animation animation = AnimationUtils.loadAnimation(this.getApplicationContext(), R.anim.translate_and_alpha);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.startAnimation(animation);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        view.startAnimation(animation);
    }

    /**
     * 报警反馈
     */
    private void communicateServer(EmergencyResponse response) {
        if (!mEmergencyAlarming) {
            return;
        }

        mEmergencyAlarming = false;

        if (mReportServerDialog == null) {
            return;
        }
        if (mReportServerDialog != null) {
            mReportServerDialog.dismiss();
        }
        //根据不同情况显示结果。
        if (response.isSuccess()) {
            mResultDialog = new MaterialDialog.Builder(this)
                    //.title("报警反馈")
                    .content(R.string.dialog_content_emergency_success)
                    .canceledOnTouchOutside(false)
                    .positiveText(R.string.dialog_positive_text)
                    .positiveColorRes(R.color.back_ground_green)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                        }
                    })
                    .dismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            mResultDialog = null;
                        }
                    })
                    .build();
            ViewUtil.removeHomeKeyListener(mResultDialog);
        } else {
            mResultDialog = new MaterialDialog.Builder(this)
                    //.title("报警反馈")
                    //.iconRes(R.drawable.warn_ring)
                    .content(R.string.dialog_content_emergency_error)
                    .canceledOnTouchOutside(false)
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_again)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            initReportServerDialog();//报警
                        }
                    })
                    .dismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            mResultDialog = null;
                        }
                    })
                    .negativeText(R.string.dialog_negative_text)
                    .build();
            ViewUtil.removeHomeKeyListener(mResultDialog);
        }
    }

    @Override
    protected void onDestroy() {
        if (mReportServerDialog != null) {
            mReportServerDialog.dismiss();
            mReportServerDialog = null;
        }
        if (mSureDialog != null) {
            mSureDialog.dismissAllowingStateLoss();
            mSureDialog = null;
        }
        super.onDestroy();
    }
}
